<template>
  <!-- 商店管理 -->
  <div class=" height-percent-100">
    <el-breadcrumb class="page-position">
      <!-- <el-breadcrumb-item>首页</el-breadcrumb-item> -->
      <el-breadcrumb-item><a href="javascript:;">商品管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="searchBox white-bk margin-b-10 ">
      <el-form class="search-form" :inline="true" :model="searchForm">
        <el-form-item label="类型">
          <el-select filterable clearable v-model="searchForm.type" placeholder="请选择">
            <el-option v-for="item in typeSelect" :key="item.value" :label="item.title" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="width:300px">
          <el-button size="small" type="primary" @click="getPageList(1)">查询</el-button>
          <el-button size="small" type="success" @click="resetSearch">重置</el-button>
          <el-button v-if="token" size="small" type="danger" @click="openModel(0)">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tableBox  ">
      <el-table :data="tableData" stripe>
        <el-table-column show-overflow-tooltip prop="rpaRobotName" label="机器人名称" min-width="140" />
        <el-table-column show-overflow-tooltip prop="developerName" label="开发者名字" min-width="140" />
        <el-table-column show-overflow-tooltip prop="version" label="版本号" min-width="140" />
        <!--<el-table-column show-overflow-tooltip prop="userNo" label="类型" min-width="120" />-->
        <el-table-column show-overflow-tooltip prop="uploadDate" label="上传日期" min-width="140" />
        <el-table-column show-overflow-tooltip fixed="right" label="操作" width="260">
          <template #default="scope">
            <!-- 窗口详情 -->
            <!-- <el-button size="small" @click.prevent="getItemInfo(scope.row.id, 2)" type="text">查看</el-button>   -->
            <!-- 页面详情 -->
            <el-button size="small" @click.prevent="toPage(scope.row.id)" type="text">查看</el-button>
            <el-button size="small" v-if="token" @click.prevent="openModel(scope.row.id)" type="text">编辑</el-button>
            <el-button size="small" v-if="token" @click.prevent="deleteItem(scope.row.id)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-box">
      <el-pagination class="flex-par" :currentPage="searchForm.pageNum" :page-size="searchForm.pageSize" :small="true"
        background="#F4F4F4" layout="total,  prev, pager, next" :total="dataTotal" @current-change="getPageList" />
    </div>
    <!-- 详情 -->
    <el-dialog v-model="modelV_2" width="800px">
      <div class="model-item-title">
        <div class="model-title">商品信息</div>
      </div>
      <div class="model-info">
        <el-form label-width="140px">
          <el-form-item label="机器人名称">
            <el-input v-model="itemInfo.rpaRobotName" disabled placeholder="请输入" />
          </el-form-item>
          <el-form-item label="开发者名字">
            <el-input v-model="itemInfo.developerName" disabled placeholder="请输入" />
          </el-form-item>
          <el-form-item label="版本号">
            <el-input v-model="itemInfo.version" disabled placeholder="请输入" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select class="width-percent-100" disabled filterable clearable v-model="itemInfo.type"
              placeholder="请选择">
              <el-option v-for="item in typeSelect" :key="item.value" :label="item.title" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="简介">
            <el-input v-model="itemInfo.content" disabled placeholder="请输入" />
          </el-form-item>
          <!-- 上传截图 -->
          <el-form-item label="截图">
            <!-- <el-upload class="upload-box" :show-file-list="false" name="pic" :action="uploadUrl1" accept=".jpg,.png"
              :headers="headers" :onSuccess="uploadSuccess" :onError="uploadError">
              <img src="../../assets/image/add-img.png" class="img-item" />
            </el-upload> -->
            <div class="img-item" v-for="item in imgList" :key="item">
              <!-- <div class="del-btn active-style" @click="deleteImg(index)">×</div> -->
              <img :src="serverUrl + item" class="img-item" />
            </div>
          </el-form-item>
          <!-- 上传.ibt文件 -->
          <el-form-item label=".ibt文件" v-if="itemInfo.rpaRobotName">
            <el-upload class="upload-box" :show-file-list="false" name="file"
              :data="{ fileName: itemInfo.rpaRobotName }" :action="uploadUrl2" accept=".ibt" :headers="headers"
              :onSuccess="uploadSuccess2" :onError="uploadError">
              <el-button size="small" v-if="itemInfo.rpaFileAddress == ''">点击上传文件</el-button>
              <span v-if="itemInfo.rpaFileAddress" class="orange-color">{{ itemInfo.rpaFileAddress }}</span>
            </el-upload>
          </el-form-item>
          <!-- 上传视频文件 -->
          <el-form-item label="视频文件" v-if="itemInfo.rpaRobotName">

            <video width="640" height="360" controls preload="metadata">
              <!-- 添加视频源 -->
              <source :src="serverUrl + itemInfo.videoAddress" type="video/mp4">
              <source :src="serverUrl + itemInfo.videoAddress" type="video/webm">

              <!-- 如果浏览器不支持 video 标签则显示的文字 -->
              <p>抱歉，您的浏览器不支持 HTML5 视频播放。</p>
            </video>



            <!-- <el-upload class="upload-box" :show-file-list="false" name="file"
              :data="{ fileName: itemInfo.rpaRobotName }" :action="uploadUrl3" accept=".mp4" :headers="headers"
              :onSuccess="uploadSuccess3" :onError="uploadError">
              <el-button size="small" v-if="itemInfo.videoAddress == ''">点击上传文件</el-button>
              <span v-if="itemInfo.videoAddress" class="orange-color">{{ itemInfo.videoAddress }}</span>
            </el-upload> -->
          </el-form-item>
          <el-form-item>
          </el-form-item>

        </el-form>
      </div>
    </el-dialog>
    <!-- 表单 -->
    <el-dialog v-model="modelV" width="800px">
      <div class="model-item-title">
        <div class="model-title">商品信息</div>
      </div>
      <div class="model-info">
        <el-form label-width="140px">
          <el-form-item label="机器人名称">
            <el-input v-model="itemInfo.rpaRobotName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="开发者名字">
            <el-input v-model="itemInfo.developerName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="版本号">
            <el-input v-model="itemInfo.version" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select class="width-percent-100" filterable clearable v-model="itemInfo.type" placeholder="请选择">
              <el-option v-for="item in typeSelect" :key="item.value" :label="item.title" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="简介">
            <el-input v-model="itemInfo.content" placeholder="请输入" />
          </el-form-item>
          <!-- 上传截图 -->
          <el-form-item label="上传截图">
            <el-upload class="upload-box" :show-file-list="false" name="pic" :action="uploadUrl1" accept=".jpg,.png"
              :data="{ type: 'screenshot' }" :headers="headers" :onSuccess="uploadSuccess" :onError="uploadError">
              <img src="../../assets/image/add-img.png" class="img-item" />
            </el-upload>
            <div class="img-item" v-for="item, index in imgList" :key="item">
              <div class="del-btn active-style" @click="deleteImg(index)">×</div>
              <img :src="serverUrl + item" class="img-item" />
            </div>
          </el-form-item>
          <!-- 上传.ibt文件 -->
          <el-form-item label="上传.ibt文件" v-if="itemInfo.rpaRobotName">
            <el-upload class="upload-box" :show-file-list="false" name="file"
              :data="{ fileName: itemInfo.rpaRobotName }" :action="uploadUrl2" accept=".ibt" :headers="headers"
              :onSuccess="uploadSuccess2" :onError="uploadError">
              <el-button size="small" v-if="itemInfo.rpaFileAddress == ''">点击上传文件</el-button>
              <span v-if="itemInfo.rpaFileAddress" class="orange-color">{{ itemInfo.rpaFileAddress }}</span>
            </el-upload>
          </el-form-item>
          <!-- 上传视频文件 -->
          <el-form-item label="上传视频文件" v-if="itemInfo.rpaRobotName">
            <el-upload class="upload-box" :show-file-list="false" name="file"
              :data="{ fileName: itemInfo.rpaRobotName }" :action="uploadUrl3" accept=".mp4" :headers="headers"
              :onSuccess="uploadSuccess3" :onError="uploadError">
              <el-button size="small" v-if="itemInfo.videoAddress == ''">点击上传文件</el-button>
              <span v-if="itemInfo.videoAddress" class="orange-color">{{ itemInfo.videoAddress }}</span>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button size="middle" type="primary" @click="submit">保存</el-button>
          </el-form-item>

        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  serverUrl, saveRpacontroller, pageSize, deleteRpa, removeIbtFun, removeImgFun,
  getSelectByType, removeUserInfo, getRpaInfo, unlockAccount
} from '@/assets/api/api.js';
import '@/assets/css/tabs.css';
export default {
  data() {
    return {
      serverUrl,
      uploadUrl1: serverUrl + "/rpaFileUpload/uploadScreenShot",//截图
      uploadUrl2: serverUrl + "/rpaFileUpload/upload",//ibt文件
      uploadUrl3: serverUrl + "/rpaFileUpload/uploadVideo",//视频文件
      headers: {
        'Access-Control-Allow-Origin': '*',
        Accept: 'application/json; charset=utf-8',
      },

      id: '',


      typeSelect: [
        { title: '安全生产', value: '1' },
        { title: '党的建设', value: '2' },
        { title: '电网建设', value: '3' },
        { title: '经营管理', value: '4' },
        { title: '营销服务', value: '5' },
      ],

      pageSize,
      modelV: false,
      modelV_2: false,
      searchForm: {
        type: '',
        pageNum: 1,
        pageSize,
      },
      dataTotal: 0,
      tableData: [],

      imgList: [],

      itemInfo: {
        rpaRobotName: '',
        version: '',
        developerName: '',
        screenShotAddress: '',
        rpaFileAddress: '',
        videoAddress: '',
        content: '',
        type: '',
      },

      token: ''
    };
  },
  methods: {
    // el-upload 不走全局 axios 拦截器，这里在使用前补齐 token
    ensureUploadAuth() {
      this.headers = Object.assign({}, this.headers, {
        Authorization: localStorage.getItem('token') || ''
      })
    },
    toPage(id) {
      this.$router.push({ path: `/manageDetail/${id}` });
    },
    uploadSuccess3(e) {
      if (!e) {
        this.$message({ message: '上传失败：服务端未返回数据', type: 'error', center: true })
        return
      }
      if (e && typeof e === 'object' && typeof e.code !== 'undefined') {
        if (e.code !== 0) {
          this.$message({ message: e.message || '上传失败', type: 'error', center: true })
          return
        }
        const val = e.data?.path || e.data || e.path || ''
        if (val) {
          this.itemInfo.videoAddress = val
        } else {
          this.$message({ message: '上传失败：未获取到文件路径', type: 'error', center: true })
        }
        return
      }
      const val = e?.path || e || ''
      if (val) {
        this.itemInfo.videoAddress = val
      } else {
        this.$message({ message: '上传失败：未获取到文件路径', type: 'error', center: true })
      }
    },
    uploadSuccess2(e) {
      if (!e) {
        this.$message({ message: '上传失败：服务端未返回数据', type: 'error', center: true })
        return
      }
      if (e && typeof e === 'object' && typeof e.code !== 'undefined') {
        if (e.code !== 0) {
          this.$message({ message: e.message || '上传失败', type: 'error', center: true })
          return
        }
        const newPath = e.data?.path || e.data || e.path || ''
        if (!newPath) {
          this.$message({ message: '上传失败：未获取到文件路径', type: 'error', center: true })
          return
        }
        if (this.itemInfo.rpaFileAddress) {
          removeIbtFun(this.itemInfo.rpaFileAddress)
            .then((res) => {
              if (res.code == 0) {
                this.itemInfo.rpaFileAddress = newPath
              }
            })
            .catch((err) => { });
        } else {
          this.itemInfo.rpaFileAddress = newPath
        }
        return
      }
      if (this.itemInfo.rpaFileAddress) {

        removeIbtFun(this.itemInfo.rpaFileAddress)
          .then((res) => {
            if (res.code == 0) {
              const pathVal = e?.path || e || ''
              if (pathVal) {
                this.itemInfo.rpaFileAddress = pathVal
              } else {
                this.$message({ message: '上传失败：未获取到文件路径', type: 'error', center: true })
              }
            }
          })
          .catch((err) => { });
      } else {

        const pathVal = e?.path || e || ''
        if (pathVal) {
          this.itemInfo.rpaFileAddress = pathVal
        } else {
          this.$message({ message: '上传失败：未获取到文件路径', type: 'error', center: true })
        }
      }
    },
    deleteImg(index) {
      removeImgFun(this.imgList[index])
        .then((res) => {
          if (res.code == 0) {
            this.imgList.splice(index, 1)
          }
        })
        .catch((err) => { });
    },
    uploadSuccess(e) {
      console.log('uploadSuccess', e)
      if (!e) {
        this.$message({ message: '上传失败：服务端未返回数据', type: 'error', center: true })
        return
      }
      if (e && typeof e === 'object' && typeof e.code !== 'undefined') {
        if (e.code !== 0) {
          this.$message({ message: e.message || '上传失败', type: 'error', center: true })
          return
        }
        const val = e.data?.path || e.data || e.path
        if (val) this.imgList.push(val)
        else this.$message({ message: '上传失败：未获取到文件路径', type: 'error', center: true })
        return
      }
      const val = e?.path || e
      if (val) this.imgList.push(val)
      else this.$message({ message: '上传失败：未获取到文件路径', type: 'error', center: true })
    },
    uploadError(e) {
      console.log('uploadError', e)
      let message = '上传失败，请稍后重试'
      if (e && e.message) {
        message = e.message
      }
      const resp = e?.response || e?.target?.response || null
      try {
        if (resp && typeof resp === 'string') {
          const json = JSON.parse(resp)
          message = json.message || json.msg || message
        } else if (resp && typeof resp === 'object') {
          const data = resp.data || resp
          if (typeof data === 'string') {
            message = data
          } else if (data && typeof data === 'object') {
            message = data.message || data.msg || message
          }
        }
      } catch (_) {}
      this.$message({ message, type: 'error', center: true })
    },
    openModel(id) {
      this.id = id
      if (id == 0) {
        this.itemInfo = {

          rpaRobotName: '',
          version: '',
          developerName: '',
          screenShotAddress: '',
          rpaFileAddress: '',
          videoAddress: '',
          content: '',
          type: '',
        }
        this.modelV = true
      } else {
        this.getItemInfo(id, 1)
      }
    },
    submit() {
      this.itemInfo.screenShotAddress = this.imgList.toString()
      let itemInfo = this.itemInfo
      for (let key in itemInfo) {
        if (itemInfo[key] == '') {
          this.$message({
            message: '请完善信息',
            type: 'error',
            center: true,
          });
          return false
        }
      }

      saveRpacontroller(this.id, itemInfo)
        .then((res) => {
          if (res.code == 0) {
            this.$message({
              message: '保存成功',
              type: 'success',
              center: true,
            });
            this.modelV = false
            this.getPageList()
          }
        })
        .catch((err) => { });
    },
    //type 1表单窗口 2详情窗口
    getItemInfo(id, type) {
      getRpaInfo({ id })
        .then((res) => {
          if (res.code == 0) {
            this.itemInfo = res.data
            this.imgList = res.data.screenShotAddress.split(',')
            if (type == 1) {
              this.modelV = true
            }
            if (type == 2) {
              this.modelV_2 = true
            }
          }
        })
        .catch((err) => { });
    },
    unlockItem(id) {
      this.$confirm('确定解锁账号吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        unlockAccount({ userId: id })
          .then((res) => {
            if (res.code == 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                center: true,
              });
              this.getPageList()
            }
          })
          .catch((err) => { });
      });
    },
    deleteItem(id) {
      this.$confirm('确定删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        deleteRpa({ id })
          .then((res) => {
            if (res.code == 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                center: true,
              });
              this.getPageList()
            }
          })
          .catch((err) => { });
      });
    },
    //   -列表
    getPageList(pageNum) {
      if (pageNum) {
        this.searchForm.pageNum = pageNum
      }
      getSelectByType(this.searchForm)
        .then((res) => {
          console.log(res)
          if (res.code == 0) {
            //console.log(res.data)
            this.tableData = res.data
            this.dataTotal = res.total
          }
        })
        .catch((err) => { });
    },
    // 重置筛选项
    resetSearch() {
      this.searchForm = {
        type: '',
        pageNum: 1,
        pageSize: this.pageSize,
      }
      this.getPageList()
    },

  },
  mounted() {
    this.ensureUploadAuth()

    this.token = localStorage.getItem('token')
    this.getPageList()
    /**
    // 组织机构
    this.$getOrgSelect((selectList) => {
      this.orgSelect = selectList
    })
    //  用户类型
    this.$getUserTypeSelect((selectList) => {
      this.userTypeSelect = selectList
    })
    //  用户角色
    this.$getRoleSelect((selectList) => {
      this.roleSelect = selectList
    })*/
  },
};
</script>
<style scoped>
.img-item {
  width: 80px;
  height: 80px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin: 0 10px 10px 0;
  position: relative;
}

.img-item img {
  width: 100%;
  height: 100%;
}

.img-item .del-btn {
  position: absolute;
  z-index: 10;
  color: white;
  background: rgba(0, 0, 0, 0.5);
  font-size: 20px;
  width: 20px;
  height: 20px;
  line-height: 18px;
  text-align: center;
  border-radius: 50%;
  right: -5px;
  top: -5px;
}
</style>